package com.qingcloud.adminbackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ImmutableMap;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.entity.config.SysDictionaryConfig;
import com.qingcloud.adminbackend.entity.equipment.StationGroupEquipmentBO;
import com.qingcloud.adminbackend.entity.equipment.SysEquipment;
import com.qingcloud.adminbackend.entity.equipment.SysEquipmentDTO;
import com.qingcloud.adminbackend.entity.stationgroup.*;
import com.qingcloud.adminbackend.mapper.*;
import com.qingcloud.adminbackend.entity.stationgroup.*;
import com.qingcloud.adminbackend.entity.sysorder.SysOrder;
import com.qingcloud.adminbackend.entity.sysorg.SysOrg;
import com.qingcloud.adminbackend.entity.sysorg.SysUserOrg;
import com.qingcloud.adminbackend.entity.sysorg.SysUserOrgMgr;
import com.qingcloud.adminbackend.entity.sysstation.StationEquipmentParam;
import com.qingcloud.adminbackend.entity.sysstationmo.SysStationMo;
import com.qingcloud.adminbackend.entity.user.SysUser;
import com.qingcloud.adminbackend.entity.usergroup.SysUsergroup;
import com.qingcloud.adminbackend.entity.usergroup.SysUsergroupDTO;
import com.qingcloud.adminbackend.entity.userrole.UserRoleVO;
import com.qingcloud.adminbackend.enums.UserRoleEnum;
import com.qingcloud.adminbackend.mapper.*;
import com.qingcloud.adminbackend.service.ISysStationGroupService;
import com.qingcloud.base.constant.SecurityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备组 服务实现类
 * </p>
 *
 * @author luozehua
 * @since 2018-11-15
 */
@Service
public class SysStationGroupServiceImpl extends ServiceImpl<SysStationGroupMapper, SysStationGroup> implements ISysStationGroupService {

    @Resource
    private SysStationGroupEquipmentMapper sysStationGroupEquipmentMapper;

    @Resource
    private SysUsergroupStationgroupMapper sysUsergroupStationgroupMapper;

    @Resource
    private SysUserStationGroupMapper sysUserStationGroupMapper;

    @Resource
    private SysOrgStationGroupMapper sysOrgStationGroupMapper;

    @Resource
    private SysUsergroupMapper sysUsergroupMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysOrgMapper sysOrgMapper;

    @Resource
    private SysUserOrgMgrMapper sysUserOrgMgrMapper;

    @Resource
    private SysUserOrgMapper sysUserOrgMapper;

    @Resource
    private SysUserStationgroupMgrstationMapper userStationgroupMgrstationMapper;

    @Resource
    private SysOrderMapper sysOrderMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysStationMoMapper sysStationMoMapper;

    @Resource
    private SysDictionaryConfigMapper sysDictionaryConfigMapper;

    /**
     * 分页查询
     *
     * @param sysStationGroup
     * @return
     */
    @Override
    public IPage<SysStationGroup> findStationGroupPage(SysStationGroupBO sysStationGroup, String userId, Boolean isAdmin) {
        Page<SysStationGroup> page = new Page<>(sysStationGroup.getCurrentPage(), sysStationGroup.getPerPage());
        List<String> allMgr = new ArrayList<>();
        List<String> orgMgrIds = new ArrayList<>();
        List<String> orgOnlyRead = new ArrayList<>();
        List<String> oriGroupIds;
        List<String> groupIdsTemp = new ArrayList<>();
        //监测点对应的设备组ID
        List<String> monitorGroupIds = new ArrayList<>();
        //设备对应的设备组ID
        List<String> equipGroupIds = new ArrayList<>();
        //客户对应的设备组ID
        List<String> orgGroupIds = new ArrayList<>();

        SysUser sysUser = sysUserMapper.selectById(userId);
        Integer adminFlag = sysUser.getAdminFlag();
        if (isAdmin || adminFlag == 1) {
            //查询所有客户
            QueryWrapper<SysOrg> orgQueryWrapper = new QueryWrapper<>();
            orgQueryWrapper.eq("delete_flag", 0);
            List<SysOrg> sysOrgs = sysOrgMapper.selectList(orgQueryWrapper);
            sysOrgs.forEach(e -> allMgr.add(e.getId()));
        } else {
            //登录用户可管理的客户及其分支机构
            List<SysOrg> allManageOrgByUser = sysUserOrgMgrMapper.findAllOrgAndChildByUser(userId, null);
            allManageOrgByUser.forEach(e -> {
                allMgr.add(e.getId());
                if (e.getManage() == 1) {
                    orgMgrIds.add(e.getId());
                } else if (e.getManage() == 0 && e.getRead() == 1) {
                    //登录用户只有读权限的客户
                    orgOnlyRead.add(e.getId());
                }
            });
            if (CollectionUtils.isEmpty(allMgr)) {
                //没有可管理的设备组
                return new Page<>();
            }
        }
        //查询登录用户能查的所有的设备组ID
        //所属的设备组
        oriGroupIds = getStationGroupIds(allMgr, groupIdsTemp);

        //监测点
        String stationIdOrName = sysStationGroup.getStationIdOrName();
        if (!StringUtils.isEmpty(stationIdOrName)) {
            List<String> groupList1 = sysStationGroupEquipmentMapper.findStations(stationIdOrName);
            if (!CollectionUtils.isEmpty(groupList1)) {
                monitorGroupIds.addAll(groupList1);
            } else {
                return new Page<>();
            }
        }

        //设备
        String equipmentId = sysStationGroup.getEquipmentId();
        if (!StringUtils.isEmpty(equipmentId)) {
            QueryWrapper<SysStationGroupEquipment> query = new QueryWrapper<>();
            query.like("equipment_id", equipmentId);
            List<SysStationGroupEquipment> sysStationGroupEquipments = sysStationGroupEquipmentMapper.selectList(query);
            List<String> groupIdList2 = new ArrayList<>();
            sysStationGroupEquipments.forEach(e -> groupIdList2.add(e.getGroupId()));
            if (!CollectionUtils.isEmpty(groupIdList2)) {
                equipGroupIds.addAll(groupIdList2);
            } else {
                return new Page<>();
            }
        }
        //客户:选择某个客户时，展示此客户和分支机构下的所有设备组；选择某个分支机构时，
        // 展示指定分支机构下的所有设备组+从上级客户授权本分支机构的可以使用的设备组
        String orgId = sysStationGroup.getOrgId();
        if (!StringUtils.isEmpty(orgId)) {
            SysOrg sysOrgById = sysOrgMapper.findSysOrgById(orgId);
            int category = sysOrgById.getCategory();
            if (category == 1) {
                //客户
                //查询旗下的分支机构
                QueryWrapper<SysOrg> query = new QueryWrapper<>();
                query.eq("parent_id", orgId);
                List<SysOrg> sysOrgs = sysOrgMapper.selectList(query);
                //选的是一级客户包括分支机构的
                List<String> orgIds = new ArrayList<>();
                sysOrgs.forEach(e -> orgIds.add(e.getId()));
                orgIds.add(orgId);
                orgGroupIds = getStationGroupIds(orgIds, null);
            } else {
                orgGroupIds = getStationGroupIds(Arrays.asList(orgId), null);
            }
            if (CollectionUtils.isEmpty(orgGroupIds)) {
                return new Page<>();
            }
        }
        if (!CollectionUtils.isEmpty(monitorGroupIds) && CollectionUtils.isEmpty(equipGroupIds) && CollectionUtils.isEmpty(orgGroupIds)) {
            oriGroupIds.retainAll(monitorGroupIds);
        } else if (!CollectionUtils.isEmpty(equipGroupIds) && CollectionUtils.isEmpty(monitorGroupIds) && CollectionUtils.isEmpty(orgGroupIds)) {
            oriGroupIds.retainAll(equipGroupIds);
        } else if (!CollectionUtils.isEmpty(orgGroupIds) && CollectionUtils.isEmpty(monitorGroupIds) && CollectionUtils.isEmpty(equipGroupIds)) {
            oriGroupIds.retainAll(orgGroupIds);
        } else if (!CollectionUtils.isEmpty(monitorGroupIds) && !CollectionUtils.isEmpty(equipGroupIds) && CollectionUtils.isEmpty(orgGroupIds)) {
            monitorGroupIds.retainAll(equipGroupIds);
            oriGroupIds.retainAll(monitorGroupIds);
        } else if (CollectionUtils.isEmpty(monitorGroupIds) && !CollectionUtils.isEmpty(equipGroupIds) && !CollectionUtils.isEmpty(orgGroupIds)) {
            equipGroupIds.retainAll(orgGroupIds);
            oriGroupIds.retainAll(equipGroupIds);
        } else if (!CollectionUtils.isEmpty(monitorGroupIds) && CollectionUtils.isEmpty(equipGroupIds) && !CollectionUtils.isEmpty(orgGroupIds)) {
            monitorGroupIds.retainAll(orgGroupIds);
            oriGroupIds.retainAll(monitorGroupIds);
        }
        if (CollectionUtils.isEmpty(oriGroupIds)) {
            return new Page<>();
        }
        IPage<SysStationGroup> stationGroupPage = baseMapper.findStationGroupPage(page, sysStationGroup, oriGroupIds);
        List<SysStationGroup> records = stationGroupPage.getRecords();
        //一级客户授权可以使用的设备组，不能修改设备组本身的内容和组内成员，可以把它直接赋权给用户或用户组
        if (isAdmin || adminFlag == 1) {
            records.forEach(e -> e.setManageEquipment(1));
        } else {
            recordsFlag:
            for (SysStationGroup record : records) {
                String id = record.getId();
                String orgId1 = record.getOrgId();
                record.setManageEquipment(1);
                if (orgMgrIds.contains(orgId1) && record.getCategory() == 1) {
                    //属于一级客户的且登录用户可管理的
                    continue;
                }
                //只要可读权限
                for (String onlyRead : orgOnlyRead) {
                    if (orgId1.equals(onlyRead)) {
                        record.setManageEquipment(-1);
                        continue recordsFlag;
                    }
                }
                //来自上级授权
                for (String up : groupIdsTemp) {
                    if (id.equals(up)) {
                        //来自一级客户授权的设备组
                        record.setManageEquipment(0);
                        continue recordsFlag;
                    }
                }
            }
        }
        return stationGroupPage;
    }

    /**
     * @param allMgr 所有的能使用的客户ID
     */
    private List<String> getStationGroupIds(List<String> allMgr, List<String> groupIdsTemp) {
        List<String> oriGroupIds = new ArrayList<>();
        QueryWrapper<SysStationGroup> query = new QueryWrapper<>();
        query.in("org_id", allMgr);
        query.eq("delete_flag", 0);
        List<SysStationGroup> sysStationGroups = baseMapper.selectList(query);
        sysStationGroups.forEach(e -> oriGroupIds.add(e.getId()));
        //从上级授权能使用的设备组
        QueryWrapper<SysOrgStationGroup> query2 = new QueryWrapper<>();
        query2.in("org_id", allMgr);
        List<SysOrgStationGroup> sysOrgStationGroups = sysOrgStationGroupMapper.selectList(query2);
        sysOrgStationGroups.forEach(e -> {
            oriGroupIds.add(e.getGroupId());
            groupIdsTemp.add(e.getGroupId());
        });
        return oriGroupIds;
    }

    /**
     * 通过ID查询
     *
     * @param id
     * @return
     */
    @Override
    public SysStationGroup findStationGroupById(String id) {
        SysStationGroup stationGroupById = baseMapper.findStationGroupById(id);
        ////查询该设备组下的设备
        //stationGroupById.setEqs(baseMapper.findStationGroupEquipments(null, null, Arrays.asList(id), null));
        return stationGroupById;
    }

    /**
     * 客户可用设备组
     *
     * @param orgId
     * @return
     */
    @Override
    public List<SysStationGroup> findStationGroup(String orgId) {
        SysOrg sysOrgById = sysOrgMapper.findSysOrgById(orgId);
        if (!StringUtils.isEmpty(sysOrgById.getParentId())) {
            orgId = sysOrgById.getParentId();
        }
        return this.baseMapper.findStationGroup(Arrays.asList(orgId));
    }

    @Override
    public List<SysStationGroup> findEqMgStationGroup(List<String> orderIds, List<String> orgIds, String userId) {
        if (CollUtil.isEmpty(orderIds) && CollUtil.isEmpty(orgIds)) {
            SysUser sysUser = sysUserMapper.selectById(userId);
            if (SecurityConstants.ADMIN_USER_NAME.equals(sysUser.getUserName())) {
                return baseMapper.selectAllGroup(2);
            } else if (sysUser.getUserType() == 1) {
                List<UserRoleVO> roleByUserId = sysUserRoleMapper.findRoleByUserId(userId);
                Integer roleId = 0;
                if (CollUtil.isNotEmpty(roleByUserId)) {
                    UserRoleVO userRoleVO = roleByUserId.get(0);
                    roleId = userRoleVO.getId();
                }
                if (UserRoleEnum.COMPANY_EQUIPMENT_MANAGER_ID.code.equals(roleId)) {
                    //设备管理权限,管理所有设备组
                    return baseMapper.selectAllGroup(2);
                } else if (UserRoleEnum.COMPANY_MANAGER_ID.code.equals(roleId)) {
                    //企业管理员，可管理的客户及分支机构下，或可管理的分支机构下的所有设备组
                    List<String> mgrOrgIds = getMgrOrgIds(userId);
                    if (CollUtil.isEmpty(mgrOrgIds)) {
                        return Collections.emptyList();
                    }
                    //没有客户只有分支机构
                    return this.baseMapper.findStationGroup(mgrOrgIds);
                } else {
                    //其他 可管理的客户/分支机构范围、设备组范围，在输入时进行模糊匹配
                    return getSysStationGroups(userId);
                }
            } else if (sysUser.getUserType() == 2) {
                return getSysStationGroups(userId);
            } else {
                return new ArrayList<>();
            }
        } else {
            List<String> tempOrgIds = new ArrayList<>();
            if (CollUtil.isNotEmpty(orderIds)) {
                QueryWrapper<SysOrder> orderQueryWrapper = new QueryWrapper<>();
                orderQueryWrapper.in("id", orderIds);
                orderQueryWrapper.eq("delete_flag", 0);
                List<SysOrder> sysOrders = sysOrderMapper.selectList(orderQueryWrapper);
                tempOrgIds = sysOrders.stream().map(SysOrder::getOrgId).collect(Collectors.toList());
            }
            tempOrgIds.addAll(orgIds);
            if (CollUtil.isNotEmpty(tempOrgIds)) {
                //查询客户下面的分支机构
                QueryWrapper<SysOrg> orgQuery = new QueryWrapper<>();
                orgQuery.in("id", tempOrgIds);
                orgQuery.in("delete_flag", 0);
                List<SysOrg> sysOrgs = sysOrgMapper.selectList(orgQuery);
                List<String> parenId = sysOrgs.stream().filter(x -> x.getCategory() == 1).map(SysOrg::getId).collect(Collectors.toList());
                QueryWrapper<SysOrg> sub = new QueryWrapper<>();
                sub.in("parent_id", parenId);
                sub.in("delete_flag", 0);
                List<SysOrg> orgs = sysOrgMapper.selectList(sub);
                List<String> subList = orgs.stream().map(SysOrg::getId).collect(Collectors.toList());
                tempOrgIds.addAll(subList);
                //查询订单所在客户
                return this.baseMapper.findStationGroup(tempOrgIds);
            } else {
                return new ArrayList<>();
            }
        }
    }

    /**
     * 可管理的客户/分支机构范围、设备组范围，在输入时进行模糊匹配
     *
     * @param userId
     * @return
     */
    private List<SysStationGroup> getSysStationGroups(String userId) {
        List<String> mgrOrgIds = getMgrOrgIds(userId);
        if (CollUtil.isEmpty(mgrOrgIds)) {
            return Collections.emptyList();
        }
        List<SysUserStationgroupMgrstation> mgrgourp = userStationgroupMgrstationMapper.selectByMap(ImmutableMap.of("user_id", userId));
        List<SysStationGroup> stationGroup = this.baseMapper.findStationGroup(mgrOrgIds);
        if (CollUtil.isEmpty(mgrgourp)) {
            return stationGroup;
        } else {
            List<String> groupIds = mgrgourp.stream().map(SysUserStationgroupMgrstation::getGroupId).collect(Collectors.toList());
            QueryWrapper<SysStationGroup> stationQuery = new QueryWrapper<>();
            stationQuery.in("id", groupIds);
            List<SysStationGroup> sysStationGroups = baseMapper.selectList(stationQuery);
            stationGroup.addAll(sysStationGroups);
            return stationGroup;
        }
    }

    private List<String> getMgrOrgIds(String userId) {
        List<SysUserOrgMgr> sysUserOrgMgrs = sysUserOrgMgrMapper.selectByMap(ImmutableMap.of("user_id", userId, "manage", 1));
        List<String> tempOrgIds = sysUserOrgMgrs.stream().map(SysUserOrgMgr::getOrgId).collect(Collectors.toList());
        if (CollUtil.isEmpty(tempOrgIds)) {
            return Collections.emptyList();
        }
        QueryWrapper<SysOrg> query = new QueryWrapper<>();
        query.in("id", tempOrgIds);
        query.eq("category", 1);
        query.eq("delete_flag", 0);
        query.eq("business_type", 2);
        List<SysOrg> sysOrgs = sysOrgMapper.selectList(query);
        if (CollUtil.isNotEmpty(sysOrgs)) {
            List<String> parent = sysOrgs.stream().map(SysOrg::getId).collect(Collectors.toList());
            QueryWrapper<SysOrg> p = new QueryWrapper<>();
            p.in("parent_id", parent);
            p.eq("category", 2);
            p.eq("delete_flag", 0);
            p.eq("business_type", 2);
            List<SysOrg> subs = sysOrgMapper.selectList(p);
            List<String> allSubs = subs.stream().map(SysOrg::getId).collect(Collectors.toList());
            tempOrgIds.addAll(allSubs);
        }
        return tempOrgIds;
    }

    /**
     * 添加设备组
     *
     * @param sysStationGroupDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addStationGroupOrg(SysStationGroupDTO sysStationGroupDTO) {
        try {
            List<String> ids = new ArrayList<>();
            ids.add(sysStationGroupDTO.getOrgId());
            this.baseMapper.deleteOrgStationGroup(ids);
            if (!StringUtils.isEmpty(sysStationGroupDTO.getGroupIds()) && sysStationGroupDTO.getGroupIds().size() > 0) {
                List<SysOrgStationGroup> sysOrgStationGroups = new ArrayList<>();
                for (String groupId : sysStationGroupDTO.getGroupIds()) {
                    SysOrgStationGroup sysOrgStationGroup = new SysOrgStationGroup();
                    sysOrgStationGroup.setOrgId(sysStationGroupDTO.getOrgId());
                    sysOrgStationGroup.setGroupId(groupId);
                    sysOrgStationGroup.setCreateBy(sysStationGroupDTO.getUserId());
                    sysOrgStationGroups.add(sysOrgStationGroup);
                }
                this.baseMapper.addStationGroupOrg(sysOrgStationGroups);
            }
        } catch (Exception e) {
            return new AjaxResult(WamingConstant.FAILURE, "设置失败");
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "设置成功");
    }

    /**
     * 添加设备组
     *
     * @param addParam    设备组添加参数
     * @param loginUserId 当前登录用户ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addStationGroup(StationgroupAddParam addParam, String loginUserId) {
        //组装设备组对象
        SysStationGroup sysStationGroup = new SysStationGroup();
        sysStationGroup.setOrgId(addParam.getOrgId());
        sysStationGroup.setCreateBy(loginUserId);
        sysStationGroup.setCreateDt(new Date());
        sysStationGroup.setModifyBy(loginUserId);
        sysStationGroup.setModifyDt(new Date());
        sysStationGroup.setName(addParam.getName());
        sysStationGroup.setDescription(addParam.getDescription());
        boolean saveResult = this.save(sysStationGroup);
        if (saveResult) {
            //检查是否有关联设备组
            List<StationEquipmentParam> stationList = addParam.getStationList();
            if (stationList != null && !stationList.isEmpty()) {
                //有关联保存设备组与设备关联信息
                SysStationGroupEquipment groupEquipment = new SysStationGroupEquipment();
                groupEquipment.setGroupId(sysStationGroup.getId());
                groupEquipment.setCreateBy(loginUserId);
                groupEquipment.setModifyBy(loginUserId);
                groupEquipment.setCreateDt(new Date());
                groupEquipment.setModifyDt(new Date());
                stationList.forEach(it -> {
                    groupEquipment.setStationId(it.getStationId());
                    groupEquipment.setEquipmentId(it.getEquipmentId());
                    sysStationGroupEquipmentMapper.insert(groupEquipment);
                });
            }
        }
        return saveResult;
    }

    /**
     * 修改设备组
     *
     * @param addParam    参数对象
     * @param loginUserId 当前登录用户ID
     * @return
     */
    @Override
    public void updateStationGroup(StationgroupAddParam addParam, String loginUserId) {
        //组装设备组对象
        SysStationGroup sysStationGroup = new SysStationGroup();
        sysStationGroup.setId(addParam.getId());
        sysStationGroup.setOrgId(addParam.getOrgId());
        sysStationGroup.setCreateBy(loginUserId);
        sysStationGroup.setCreateDt(new Date());
        sysStationGroup.setModifyBy(loginUserId);
        sysStationGroup.setModifyDt(new Date());
        sysStationGroup.setName(addParam.getName());
        sysStationGroup.setDescription(addParam.getDescription());
        int i = baseMapper.updateById(sysStationGroup);
        if (i > 0) {
            List<StationEquipmentParam> stationList = addParam.getStationList();
            //删除原有的关系
            sysStationGroupEquipmentMapper.deleteByMap(ImmutableMap.of("group_id", sysStationGroup.getId()));
            //建立关系
            //添加设备与设备组的关系
            SysStationGroupEquipment ge = new SysStationGroupEquipment();
            ge.setGroupId(sysStationGroup.getId());
            ge.setCreateBy(loginUserId);
            ge.setCreateDt(new Date());
            ge.setModifyDt(new Date());
            ge.setModifyBy(loginUserId);
            stationList.forEach(e -> {
                ge.setEquipmentId(e.getEquipmentId());
                ge.setStationId(e.getStationId());
                sysStationGroupEquipmentMapper.insert(ge);
            });
        }
    }

    /**
     * 获取用户能够绑定到这个设备组的设备列表（不是目标设备组的设备）
     *
     * @param orgId
     * @param groupId
     * @param query
     * @param currentPage
     * @param prePage
     * @param oriGroupId
     * @return
     */
    @Override
    public IPage<SysEquipment> findSAddtationGroupEquipment(String orgId, String groupId, String query, Integer currentPage, Integer prePage, String oriGroupId) {
        List<String> groupIds = new ArrayList<>();
        if (!StringUtils.isEmpty(orgId)) {
            //根据ORGID查询
            SysOrg sysOrg = sysOrgMapper.selectById(orgId);
            if (sysOrg.getCategory() == 1) {
                //客户
                //查询改客户下的设备组
                QueryWrapper<SysStationGroup> wapper = new QueryWrapper();
                wapper.eq("org_id", orgId);
                List<SysStationGroup> sysOrgStationGroups = baseMapper.selectList(wapper);
                sysOrgStationGroups.forEach(e -> {
                    groupIds.add(e.getId());
                    //  orgIds.add(e.getOrgId());
                });
            } else if (sysOrg.getCategory() == 2) {
                //分支机构
                //客户可用组织
                //查询改客户下的设备组
                QueryWrapper<SysOrgStationGroup> wapper = new QueryWrapper();
                wapper.eq("org_id", orgId);
                List<SysOrgStationGroup> sysOrgStationGroups = sysOrgStationGroupMapper.selectList(wapper);
                sysOrgStationGroups.forEach(e -> {
                    groupIds.add(e.getGroupId());
                    //  orgIds.add(e.getOrgId());
                });
            }
        }
        Page<SysEquipment> page = new Page<>(currentPage, prePage);
        return page.setRecords(baseMapper.findAddStationGroupEquipments(page, query, groupId, oriGroupId, groupIds));
    }

    /**
     * 查询组织下的设备
     *
     * @param groupId
     * @param currentPage
     * @param prePage
     * @return
     */
    @Override
    public IPage<SysEquipmentDTO> findStationGroupEquipment(String groupId, Integer currentPage, Integer prePage) {
        Page<SysEquipmentDTO> page = new Page<>(currentPage, prePage);
        Page<SysEquipmentDTO> list = page.setRecords(baseMapper.findStationGroupEquipments(page, groupId));
        List<SysEquipmentDTO> records = list.getRecords();
        records.forEach(it -> {
            if (it != null) {
                it.setEquipmentType(equipmentType(it.getEquipmentType(), it.getWorkType()));
                String moId = it.getMoId();
                getAddress(it, moId);
            }
        });
        return list;
    }

    /**
     * 设备组内添加设备
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> addEquipment(SysStationGroupEquipmentParam equipmentParam, String userId) {
        String groupId = equipmentParam.getGroupId();
        List<Map<String, String>> eqIds = equipmentParam.getEqId2staionIds();
        //查询该设备组是否已经绑定该设备
        //添加设备与设备组的关系
        SysStationGroupEquipment ge = new SysStationGroupEquipment();
        ge.setGroupId(groupId);
        ge.setCreateBy(userId);
        ge.setCreateDt(new Date());
        ge.setModifyDt(new Date());
        ge.setModifyBy(userId);
        StringBuilder sb = new StringBuilder();
        List<Integer> rs = new ArrayList<>();
        eqIds.forEach(e -> {
            String equipmentId = e.get("equipmentId");
            String stationId = e.get("stationId");
            ge.setEquipmentId(equipmentId);
            ge.setStationId(stationId);
            QueryWrapper<SysStationGroupEquipment> wapper = new QueryWrapper<>();
            wapper.eq("group_id", groupId)
                    .and(w -> w.eq("equipment_id", equipmentId))
                    .and(w2 -> w2.eq("station_id", stationId));
            Long integer = sysStationGroupEquipmentMapper.selectCount(wapper);
            if (integer <= 0) {
                int insert = sysStationGroupEquipmentMapper.insert(ge);
                rs.add(insert);
            } else {
                sb.append(equipmentId).append(",");
            }
        });
        Map<String, Object> result = new HashMap<>();
        result.put("res2", sb.toString());
        result.put("res1", rs);
        return result;
    }

    /**
     * 设备组内移除设备
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeEquipment(SysStationGroupEquipmentParam equipmentParam) {
        String groupId = equipmentParam.getGroupId();
        List<Map<String, String>> eqIds = equipmentParam.getEqId2staionIds();
        eqIds.forEach(eq -> {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("group_id", groupId);
            wrapper.eq("station_id", eq.get("stationId"));
            wrapper.eq("equipment_id", eq.get("equipmentId"));
            sysStationGroupEquipmentMapper.delete(wrapper);
        });
    }

    @Override
    public List<SysStationGroup> findStationGroupByOrgId(String orgId) {
        //查询客户
        SysOrg sysOrg = sysOrgMapper.selectById(orgId);
        if (sysOrg.getCategory() == 1) {
            //一级组织（此组织内的设备组）以及下面的分支机构设备组
//            List<String> orgIdList = sysOrgMapper.findChildSysOrgListV2(Arrays.asList(sysOrg.getId()))
//                    .stream().map(SysOrg::getId).collect(Collectors.toList());
//            orgIdList.add(sysOrg.getId());
            QueryWrapper<SysStationGroup> wapper = new QueryWrapper<>();
            wapper.eq("org_id", sysOrg.getId());
            return baseMapper.selectList(wapper);
        } else {
            //分支机构
            QueryWrapper<SysStationGroup> wapper = new QueryWrapper<>();
            wapper.eq("org_id", orgId);
            List<SysStationGroup> sysStationGroups = baseMapper.selectList(wapper);
            //从上级获权能使用的设备组
            List<SysOrgStationGroup> orgStationGroups = sysOrgStationGroupMapper.selectByMap(ImmutableMap.of("org_id", orgId));
            List<String> gourpIds = new ArrayList<>();
            orgStationGroups.forEach(e -> gourpIds.add(e.getGroupId()));
            if (!CollectionUtils.isEmpty(gourpIds)) {
                QueryWrapper<SysStationGroup> wapper2 = new QueryWrapper<>();
                wapper2.in("id", gourpIds);
                List<SysStationGroup> sysStationGroups1 = baseMapper.selectList(wapper2);
                sysStationGroups.addAll(sysStationGroups1);
            }
            return sysStationGroups;
        }

    }

    /**
     * 新增用户授权的时候获取的设备组列表
     *
     * @param orgId
     * @return
     */
    @Override
    public List<SysStationGroup> findStationGroup2AuthUser(String orgId, String userId, Boolean isAdmin) {
        //当前登录用户有写权限的客户或分支机构
        SysUser sysUser = sysUserMapper.selectById(userId);
        Integer adminFlag = sysUser.getAdminFlag();
        List<String> loginUserOrgMgrIds = new ArrayList<>();
        if (!isAdmin && adminFlag != 1) {
            //超级管理员或者完全管理员
            //获取当前登录用户的
            //登录用户的有写权限的
            //登录用户所属客户
            //List<SysUserOrg> userOrg = sysUserOrgMapper.selectByMap(ImmutableMap.of("user_id", userId));
            // userOrg.forEach(e -> loginUserOrgMgrIds.add(e.getOrgId()));
            //登录用户有写权限的客户
            List<SysOrg> sysUserOrgMgrs = sysUserOrgMgrMapper.findAllOrgAndChildByUser(userId, null)
                    .stream().filter(it -> WamingConstant.ONE.equals(it.getManage())).collect(Collectors.toList());
            sysUserOrgMgrs.forEach(e -> loginUserOrgMgrIds.add(e.getId()));
        }

        QueryWrapper<SysOrg> query = new QueryWrapper<>();
        query.eq("id", orgId);
        query.eq("delete_flag", "0");
        SysOrg sysOrg = sysOrgMapper.selectOne(query);
        List<String> orgIds = new ArrayList<>();
        orgIds.add(sysOrg.getId());
        if (sysOrg != null && sysOrg.getCategory() == 1) {
            //一级客户，查询下面的子节点
            QueryWrapper<SysOrg> subQuery = new QueryWrapper<>();
            subQuery.eq("parent_id", sysOrg.getId());
            subQuery.eq("delete_flag", 0);
            List<SysOrg> sysOrgs = sysOrgMapper.selectList(subQuery);
            for (SysOrg org : sysOrgs) {
                orgIds.add(org.getId());
            }
        } else if (sysOrg != null && sysOrg.getCategory() == 2) {
            orgIds.add(sysOrg.getParentId());
        } else {
            return Collections.emptyList();
        }
        if (!isAdmin && adminFlag != 1) {
            orgIds = orgIds.stream().filter(it -> loginUserOrgMgrIds.contains(it)).collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(orgIds)) {

            List<SysStationGroup> ownList = baseMapper.selectStationGroups(orgIds, null);
            //上级授权的设备组ID
            QueryWrapper<SysOrgStationGroup> queryWrapper = new QueryWrapper();
            queryWrapper.in("org_id", orgIds);
            List<SysOrgStationGroup> authOrgList = sysOrgStationGroupMapper.selectList(queryWrapper);
            List<String> gidList = authOrgList.stream()
                    .map(SysOrgStationGroup::getGroupId).collect(Collectors.toList());
            if (!gidList.isEmpty()) {
                //从上级授权的
                List<SysStationGroup> authList = baseMapper.selectStationGroups(null, gidList);
                ownList.addAll(authList);
            }
            Map<String, List<SysStationGroup>> collect = ownList.stream().collect(Collectors.groupingBy(SysStationGroup::getId));
            return collect.values().stream().map(it -> it.get(0)).collect(Collectors.toList());
        } else {
            return Collections.emptyList();
        }
    }

    /**
     * 根据用户ID查询已经授权给用户的设备组
     *
     * @param userId 用户ID
     */
    @Override
    public List<StationgroupAuthDTO> findByUserId(String userId) {
        return this.baseMapper.findAuthByUserId(userId);
    }

    /**
     * 根据用户组ID查询已经授权给用户的设备组
     *
     * @param usergroupId 用户组ID
     */
    @Override
    public List<StationgroupAuthDTO> findByUsergroupId(String usergroupId) {
        return this.baseMapper.findAuthByUsergroupId(usergroupId);
    }

    /**
     * 订单下的设备及设备组下的设备
     *
     * @param stationGroupEquipmentBO
     * @return
     */
    @Override
    public IPage<SysEquipmentDTO> findStationGroupEquipmentList(StationGroupEquipmentBO stationGroupEquipmentBO) {
        SysOrg sysOrgById = sysOrgMapper.findSysOrgById(stationGroupEquipmentBO.getOrgId());
        if (!StringUtils.isEmpty(sysOrgById)) {
            stationGroupEquipmentBO.setCategory(sysOrgById.getCategory());
        }
        Page<SysEquipmentDTO> page = new Page<>(stationGroupEquipmentBO.getCurrentPage(), stationGroupEquipmentBO.getPerPage());
        IPage<SysEquipmentDTO> list = this.baseMapper.findStationGroupEquipmentList(page, stationGroupEquipmentBO);
        List<SysEquipmentDTO> records = list.getRecords();
        records.forEach(it -> {
            it.setEquipmentType(equipmentType(it.getEquipmentType(), it.getWorkType()));
            String moId = it.getMoId();
            getAddress(it, moId);
        });
        return list;
    }

    private void getAddress(SysEquipmentDTO it, String moId) {
        if (StrUtil.isNotBlank(moId)) {
            int length = moId.length();
            String address = "";
            for (int i = 0; i < length / 5; i++) {
                String tempId = moId.substring(0, 5 * (i + 1));
                SysStationMo mo = sysStationMoMapper.selectById(tempId);
                if (mo != null) {
                    address += mo.getCapation().concat("-");
                }
            }
            if (StrUtil.isNotBlank(address)) {
                it.setAddress(address.substring(0, address.length() - 1));
            }
        }
    }

    public String equipmentType(String stechType, Integer workType) {
        if (StringUtils.isEmpty(stechType)) {
            return null;
        }
        List<SysDictionaryConfig> config = new ArrayList<>();
        if (workType == 1) {
            config = sysDictionaryConfigMapper.findByType(7);
        } else if (workType == 2) {
            config = sysDictionaryConfigMapper.findByType(14);
        }
        if (CollUtil.isNotEmpty(config)) {
            for (SysDictionaryConfig c : config) {
                if (stechType.equals(c.getCode())) {
                    return c.getName();
                }
            }
        }
        return null;
    }


    /**
     * 删除设备组
     *
     * @param groupIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteStationGroup(List<String> groupIds) {
        boolean remove = removeByIds(groupIds);
        if (remove) {
            //删除下面的设备
            sysStationGroupEquipmentMapper.removeByGroupIds(groupIds);
            groupIds.forEach(groupId -> {
                Map<String, Object> param = new HashMap<>();
                param.put("stationgroup_id", groupId);
                //删除用户组关系
                sysUsergroupStationgroupMapper.deleteByMap(param);
                //删除客户关系(客户可用设备组)
                param.clear();
                param.put("group_id", groupId);
                sysOrgStationGroupMapper.deleteByMap(param);
                //删除用户关系
                sysUserStationGroupMapper.deleteByMap(param);
            });
        }
        return remove;
    }

    /**
     * 授权
     *
     * @param id
     * @return
     */
    @Override
    public JSONObject findAuthStationGroup(String id, String userId, Boolean isAdmin) {
        JSONObject result = new JSONObject();
        //当前登录用户有写权限的客户或分支机构
        SysUser sysUser = sysUserMapper.selectById(userId);
        Integer adminFlag = sysUser.getAdminFlag();
        if (!isAdmin && adminFlag == 1) {
            isAdmin = true;
        }
        List<String> loginUserOrgMgrIds = new ArrayList<>();
        if (!isAdmin) {
            //超级管理员或者完全管理员
            //获取当前登录用户的
            //登录用户的有写权限的
            List<SysOrg> sysUserOrgMgrs = sysUserOrgMgrMapper.findAllOrgAndChildByUser(userId, null)
                    .stream().filter(it -> WamingConstant.ONE.equals(it.getManage())).collect(Collectors.toList());
            sysUserOrgMgrs.forEach(e -> loginUserOrgMgrIds.add(e.getId()));
            if (CollectionUtils.isEmpty(sysUserOrgMgrs)) {
                return result;
            }
        }
        //查询设备基本信息
        SysStationGroup sysStationGroup = baseMapper.findStationGroupById(id);
        if (sysStationGroup == null) {
            return null;
        }
        String orgId = sysStationGroup.getOrgId();
        //如果是一级组织，设备组只能授权给本组织内用户和用户组，或下级组织内的用户和用户组
        SysOrg sysOrg = sysOrgMapper.selectById(orgId);
        List<String> orgIds = new ArrayList<>();
        orgIds.add(orgId);
        Map<String, Object> param = new HashMap<>();
        if (sysOrg != null && sysOrg.getCategory() == 1) {
            if (isAdmin || loginUserOrgMgrIds.contains(orgId)) {
                //此设备组所属组织是客户（一级组织）时，设备组只能授权给本组织内用户和用户组，或下级组织内的用户和用户组
                param.put("parent_id", orgId);
                param.put("delete_flag", 0);
                List<SysOrg> sysOrgs = sysOrgMapper.selectByMap(param);
                for (SysOrg temp : sysOrgs) {
                    orgIds.add(temp.getId());
                }
            }
        } else if (sysOrg != null && sysOrg.getCategory() == 2) {
            //此设备组所属组织是分支机构（二级组织）时，设备组只能授权给本组织内用户和用户组，或授权给上级组织内的用户和用户组。
            orgIds.add(sysOrg.getParentId());
        }
        //设备组被授权的分支机构
        List<SysOrgStationGroup> orgs = sysOrgStationGroupMapper.selectByMap(ImmutableMap.of("group_id", sysStationGroup.getId()));
        for (SysOrgStationGroup org : orgs) {
            orgIds.add(org.getOrgId());
        }
        List<SysUsergroupDTO> sysUsergroups = Collections.emptyList();
        List<SysUser> sysUsers = Collections.emptyList();
        //前登录用户有写权限的客户或分支机构内的用户和用户组。
        if (!isAdmin && adminFlag != 1) {
            orgIds = orgIds.stream().filter(it -> loginUserOrgMgrIds.contains(it)).collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(orgIds)) {
            //查询用户组信息
            sysUsergroups = sysUsergroupMapper.findUserGroupByOrgId(orgIds);
            //查询用户信息
            sysUsers = sysUserMapper.findUserByOrgIds(orgIds, null);
        }
        result.put("userGroups", sysUsergroups);
        result.put("users", sysUsers);
        return result;
    }

    private List<String> findAllParent(String parentId) {
        List<String> result = new ArrayList<>();
        SysOrg parent = sysOrgMapper.selectById(parentId);
        result.add(parent.getId());
        if (parent != null && !StringUtils.isEmpty(parent.getParentId())) {
            return findAllParent(parent.getParentId());
        }
        return result;
    }

    /**
     * 设备组授权给用户组或用户
     *
     * @param stationgroupAuthParam  授权对象
     * @param loginUserId            当前登录用户ID
     * @param haveStationgroupIdList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult authStationGroup(StationgroupAuthParam stationgroupAuthParam, String loginUserId, List<String> haveStationgroupIdList) {
        //获取设备组ID列表
        List<String> stationgroupIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(stationgroupAuthParam.getStationgroupIds())) {
            stationgroupIdList = Arrays.stream(stationgroupAuthParam.getStationgroupIds().split(",")).collect(Collectors.toList());
            stationgroupIdList = stationgroupIdList.stream().filter(e -> !e.contains("_group")).collect(Collectors.toList());
        }
        //获取用户组ID列表
        List<String> usergroupIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(stationgroupAuthParam.getUsergroupIds())) {
            usergroupIdList = Arrays.stream(stationgroupAuthParam.getUsergroupIds().split(",")).collect(Collectors.toList());
        }
        //获取用户ID列表
        List<String> userIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(stationgroupAuthParam.getUserIds())) {
            userIdList = Arrays.stream(stationgroupAuthParam.getUserIds().split(",")).collect(Collectors.toList());
        }
        //先检查设备组是否需要授权
        //是否保存设备组和分支机构的授权信息
        boolean isSave = false;
        if (stationgroupAuthParam.getIsCheck() != 1) {
            //不需要检查时，直接保存
            isSave = true;
        }
        //存储需要重新授权的设备组和客户名称
        Set<String> orgNameSet = new HashSet<>();
        Set<String> stationgroupNameSet = new HashSet<>();
        //设备组不为空的时候才需要确认
        if (!stationgroupIdList.isEmpty()) {
            boolean finalIsSave = isSave;
            for (String sgid : stationgroupIdList) {
                userIdList.forEach(uid -> {
                    Map<String, String> result = authCheckUserOrgAndStationgroupOrg(sgid, uid, finalIsSave, loginUserId);
                    if (result != null) {
                        orgNameSet.add(result.get("orgName"));
                        stationgroupNameSet.add(result.get("stationgroupName"));
                    }
                });
                usergroupIdList.forEach(ugid -> {
                    Map<String, String> result = authCheckUsergroupOrgAndStationgroupOrg(sgid, ugid, finalIsSave, loginUserId);
                    if (result != null) {
                        orgNameSet.add(result.get("orgName"));
                        stationgroupNameSet.add(result.get("stationgroupName"));
                    }
                });
            }
        }
        if (stationgroupAuthParam.getIsCheck() == 1) {
            //需要检查时，判断是否有授权提示
            if (!orgNameSet.isEmpty() && !stationgroupNameSet.isEmpty()) {
                //有分支机构需要授权的提示时，直接返回
                return new AjaxResult(WamingConstant.CONFIRM_CODE, "",
                        ImmutableMap.of("orgNameSet", orgNameSet, "stationgroupNameSet", stationgroupNameSet));
            }
        }
        final List<String> finalStationgroupIdList = stationgroupIdList;
        if (stationgroupAuthParam.getType() == 0) {
            //用户或用户组授权设备组，用户或用户组ID是一个，也就是先清除这个用户或用户组下的设备组
            //如果用户组ID不为空
            if (!usergroupIdList.isEmpty()) {
                //先删除用户组关联的设备组
                usergroupIdList.forEach(it -> {
                    QueryWrapper<SysUserGroupStationGroup> deleteWrapper = new QueryWrapper<>();
                    deleteWrapper.in("stationgroup_id", haveStationgroupIdList).eq("usergroup_id", it);
                    sysUsergroupStationgroupMapper.delete(deleteWrapper);
                });
                //有设备组ID则插入设备组ID
                if (!stationgroupIdList.isEmpty()) {
                    usergroupIdList.forEach(it -> {
                        SysUserGroupStationGroup ugsg = new SysUserGroupStationGroup();
                        ugsg.setCreateBy(loginUserId);
                        ugsg.setCreateDt(new Date());
                        ugsg.setModifyDt(new Date());
                        ugsg.setModifyBy(loginUserId);
                        ugsg.setUserGroupId(it);
                        finalStationgroupIdList.forEach(stationgroupId -> {
                            ugsg.setStationGroupId(stationgroupId);
                            sysUsergroupStationgroupMapper.insert(ugsg);
                        });
                    });
                }
            }
            //如果用户ID不为空
            if (!userIdList.isEmpty()) {
                //先删除用户组关联的设备组
                userIdList.forEach(it -> {
                    QueryWrapper<SysUserStationGroup> deleteWrapper = new QueryWrapper<>();
                    deleteWrapper.in("group_id", haveStationgroupIdList).eq("user_id", it);
                    sysUserStationGroupMapper.delete(deleteWrapper);
                });
                //有设备组ID则插入设备组ID
                if (!stationgroupIdList.isEmpty()) {
                    userIdList.forEach(it -> {
                        SysUserStationGroup usg = new SysUserStationGroup();
                        usg.setCreateBy(loginUserId);
                        usg.setModifyBy(loginUserId);
                        usg.setUserId(it);
                        finalStationgroupIdList.forEach(stationgroupId -> {
                            usg.setGroupId(stationgroupId);
                            sysUserStationGroupMapper.insert(usg);
                        });
                    });
                }
            }
        } else {
            //设备组授权给用户和用户组，设备组ID是一个，也就是要先清除这个设备组关联的用户组和用户
            for (String sgId : stationgroupIdList) {
                //先删除设备组关联的用户和用户组
                sysUsergroupStationgroupMapper.deleteByMap(ImmutableMap.of("stationgroup_id", sgId));
                sysUserStationGroupMapper.deleteByMap(ImmutableMap.of("group_id", sgId));
                SysUserGroupStationGroup ugsg = new SysUserGroupStationGroup();
                ugsg.setCreateBy(loginUserId);
                ugsg.setCreateDt(new Date());
                ugsg.setModifyDt(new Date());
                ugsg.setModifyBy(loginUserId);
                ugsg.setStationGroupId(sgId);
                usergroupIdList.forEach(it -> {
                    ugsg.setUserGroupId(it);
                    sysUsergroupStationgroupMapper.insert(ugsg);
                });
                SysUserStationGroup usg = new SysUserStationGroup();
                usg.setCreateBy(loginUserId);
                usg.setModifyBy(loginUserId);
                usg.setGroupId(sgId);
                userIdList.forEach(it -> {
                    usg.setUserId(it);
                    sysUserStationGroupMapper.insert(usg);
                });
            }
        }

        return new AjaxResult(WamingConstant.SUCCESS, "", "");
    }

    /**
     * 授权时检查设备组的所属客户和用户组所属客户关系
     *
     * @param stationgroupId 设备组ID
     * @param usergroupId    用户组ID
     * @param isSave         是否保存授权信息
     * @param loginUserId    当前登录用户ID
     */
    private Map<String, String> authCheckUsergroupOrgAndStationgroupOrg(String stationgroupId, String usergroupId, boolean isSave, String loginUserId) {
        //设备组信息
        SysStationGroup stationGroup = baseMapper.selectById(stationgroupId);
        //用户组信息
        SysUsergroup usergroup = sysUsergroupMapper.selectById(usergroupId);
        //用户组所属客户信息
        SysOrg sysOrg = sysOrgMapper.selectById(usergroup.getOrgId());
        //如果设备组所属客户是用户组所属客户上级时
        if (stationGroup.getOrgId().equals(sysOrg.getParentId())) {
            //检查用户组所属客户是否授权过
            List<SysOrgStationGroup> sysOrgStationGroupList = sysOrgStationGroupMapper.selectByMap(ImmutableMap.of("org_id", sysOrg.getId(),
                    "group_id", stationgroupId));
            //结果是空的，说明没有授权
            if (sysOrgStationGroupList.isEmpty()) {
                if (!isSave) {
                    return ImmutableMap.of("stationgroupName", stationGroup.getName(), "orgName", sysOrg.getName());
                } else {
                    //保存授权信息
                    SysOrgStationGroup sysOrgStationGroup = new SysOrgStationGroup();
                    sysOrgStationGroup.setOrgId(sysOrg.getId());
                    sysOrgStationGroup.setGroupId(stationgroupId);
                    sysOrgStationGroup.setCreateBy(loginUserId);
                    sysOrgStationGroup.setModifyBy(loginUserId);
                    sysOrgStationGroupMapper.insert(sysOrgStationGroup);
                }
            }
        }
        //符合授权条件返回空
        return null;
    }

    /**
     * 授权时检查设备组的所属客户和用户组所属客户关系
     *
     * @param stationgroupId 设备组ID
     * @param userId         用户ID
     * @param isSave         是否保存授权信息
     * @param loginUserId    当前登录用户ID
     */
    private Map<String, String> authCheckUserOrgAndStationgroupOrg(String stationgroupId, String userId, boolean isSave, String loginUserId) {
        //设备组信息
        SysStationGroup stationGroup = baseMapper.selectById(stationgroupId);
        //用户所属客户信息
        SysUserOrg sysUserOrg = sysUserOrgMapper.selectByMap(ImmutableMap.of("user_id", userId)).get(0);
        SysOrg sysOrg = sysOrgMapper.selectById(sysUserOrg.getOrgId());
        //如果设备组所属客户是用户组所属客户上级时
        if (stationGroup.getOrgId().equals(sysOrg.getParentId())) {
            //检查用户组所属客户是否授权过
            List<SysOrgStationGroup> sysOrgStationGroupList = sysOrgStationGroupMapper.selectByMap(ImmutableMap.of("org_id", sysOrg.getId(),
                    "group_id", stationgroupId));
            if (sysOrgStationGroupList.isEmpty()) {
                if (!isSave) {
                    return ImmutableMap.of("stationgroupName", stationGroup.getName(), "orgName", sysOrg.getName());
                } else {
                    //保存授权信息
                    SysOrgStationGroup sysOrgStationGroup = new SysOrgStationGroup();
                    sysOrgStationGroup.setOrgId(sysOrg.getId());
                    sysOrgStationGroup.setGroupId(stationgroupId);
                    sysOrgStationGroup.setCreateBy(loginUserId);
                    sysOrgStationGroup.setModifyBy(loginUserId);
                    sysOrgStationGroupMapper.insert(sysOrgStationGroup);
                }
            }
        }
        //符合授权条件返回空
        return null;
    }

    @Override
    public List<SysUsergroup> findLikeUserGroup(String query) {
        List<SysUsergroup> sysUsergroups;
        if (StringUtils.isEmpty(query)) {
            sysUsergroups = sysUsergroupMapper.selectList(null);
        } else {
            QueryWrapper<SysUsergroup> group = new QueryWrapper<>();
            group.like("name", query);
            sysUsergroups = sysUsergroupMapper.selectList(group);
        }
        return sysUsergroups;
    }

    @Override
    public List<SysUser> findLikeUser(String query) {
        List<SysUser> sysUsers;
        if (StringUtils.isEmpty(query)) {
            sysUsers = sysUserMapper.selectList(null);
        } else {
            QueryWrapper<SysUser> group = new QueryWrapper<>();
            group.like("user_name", query)
                    .or().like("full_name", query)
                    .or().like("mobileno", query);
            sysUsers = sysUserMapper.selectList(group);
        }
        return sysUsers;
    }

    @Override
    public IPage<SysUser> findUserPageByGroup(String groupId, Integer currentPage, Integer prePage) {
        Page<SysUser> page = new Page<>(currentPage, prePage);
        return sysUsergroupMapper.findUserPageByGroupId(page, groupId);
    }


    /**
     * 已绑定的设备
     *
     * @param orgId
     * @return
     */
    @Override
    public List<SysStationGroup> findMyStationGroup(String orgId) {
        return this.baseMapper.findMyStationGroup(orgId);
    }


    /**
     * 根据设备组ID查询已经被授权的用户组和用户
     *
     * @param groupId
     * @return
     */
    @Override
    public JSONObject findAuthedUsersAndUserGroups(String groupId) {
        //用户
        QueryWrapper<SysUserStationGroup> usQuery = new QueryWrapper<>();
        usQuery.eq("group_id", groupId);
        List<SysUserStationGroup> sysUserStationGroups = sysUserStationGroupMapper.selectList(usQuery);
        List<String> userIds = new ArrayList<>();
        sysUserStationGroups.forEach(e -> userIds.add(e.getUserId()));
        List<SysUser> userByIds = Collections.EMPTY_LIST;
        if (!CollectionUtils.isEmpty(userIds)) {
            userByIds = sysUserMapper.findUserByIds(userIds);
        }
        //用户组
        QueryWrapper<SysUserGroupStationGroup> ussQuery = new QueryWrapper<>();
        ussQuery.eq("stationgroup_id", groupId);
        List<SysUserGroupStationGroup> sysUserGroupStationGroups = sysUsergroupStationgroupMapper.selectList(ussQuery);
        List<String> userGroupIds = new ArrayList<>();
        sysUserGroupStationGroups.forEach(e -> userGroupIds.add(e.getUserGroupId()));
        List<SysUsergroupDTO> sysUsergroups = Collections.EMPTY_LIST;
        if (!CollectionUtils.isEmpty(userGroupIds)) {
            sysUsergroups = sysUsergroupMapper.findUserGroupByIds(userGroupIds);
        }
        JSONObject result = new JSONObject();
        result.put("userGroups", sysUsergroups);
        result.put("users", userByIds);
        return result;
    }

    /**
     * 设备管理权限的设备组授权给用户
     *
     * @param stationgroupAuthParam 设备组和用户信息
     */
    @Override
    public void authStationManage(StationgroupAuthParam stationgroupAuthParam, String loginUserId) {
        //当前登录用户ID
        //获取设备组ID列表
        List<String> stationgroupIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(stationgroupAuthParam.getStationgroupIds())) {
            stationgroupIdList = Arrays.stream(stationgroupAuthParam.getStationgroupIds().split(",")).collect(Collectors.toList());
        }

        //获取用户ID列表
        List<String> userIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(stationgroupAuthParam.getUserIds())) {
            userIdList = Arrays.stream(stationgroupAuthParam.getUserIds().split(",")).collect(Collectors.toList());
        }
        //有用户ID时才保存
        if (!userIdList.isEmpty()) {
            for (String userId : userIdList) {
                //先删除用户原有的关系数据
                userStationgroupMgrstationMapper.deleteByMap(ImmutableMap.of("user_id", userId));
                stationgroupIdList.forEach(groupId -> {
                    SysUserStationgroupMgrstation mgrstation = new SysUserStationgroupMgrstation();
                    mgrstation.setCreateBy(loginUserId);
                    mgrstation.setModifyBy(loginUserId);
                    mgrstation.setUserId(userId);
                    mgrstation.setGroupId(groupId);
                    userStationgroupMgrstationMapper.insert(mgrstation);
                });
            }
        }
    }

    /**
     * 设备管理权限授权给用户时可用设备组列表
     *
     * @param orgId 用户所属组织ID
     * @return 设备组列表
     */
    @Override
    public List<SysStationGroup> findAuthStationgroupManage(String orgId, String loginUserId, Boolean isAdmin) {
        if (!isAdmin) {
            //不是admin，查看是否是完全管理权限
            SysUser sysUser = sysUserMapper.selectById(loginUserId);
            if (WamingConstant.ONE.equals(sysUser.getAdminFlag())) {
                isAdmin = true;
            }
        }
        //可管理客户ID
        List<String> manageOrgIdList = new ArrayList<>();
        List<String> manageOneList;
        if (!isAdmin) {
            //可管理的一级客户ID
            manageOneList = sysUserOrgMgrMapper.findAllOrgAndChildByUser(loginUserId, null)
                    .stream().filter(it -> WamingConstant.ONE.equals(it.getManage()) && WamingConstant.ONE.equals(it.getCategory()))
                    .map(SysOrg::getId)
                    .collect(Collectors.toList());
            if (manageOneList.isEmpty()) {
                //没有可管理的客户，直接返回空
                return new ArrayList<>();
            }
            //找到所有可管理客户下分支机构
            List<String> childIdList = sysOrgMapper.findChildSysOrgListV2(manageOneList).stream().map(SysOrg::getId).collect(Collectors.toList());
            //组装所有可管理客户ID
            manageOrgIdList.addAll(manageOneList);
            manageOrgIdList.addAll(childIdList);
        } else {
            //所有的一级客户
            manageOneList = sysOrgMapper.selectByMap(ImmutableMap.of("category", 1, "delete_flag", 0))
                    .stream().map(SysOrg::getId).collect(Collectors.toList());
        }
        //查看用户所属客户信息
        SysOrg sysOrg = sysOrgMapper.selectById(orgId);
        //用户可用的组织ID列表
        List<String> stationgroupOrgIdList = new ArrayList<>();
        stationgroupOrgIdList.add(sysOrg.getId());
        //如果是一级客户，能使用本组织内设备组，或下级组织内的设备组
        if (WamingConstant.ONE.equals(sysOrg.getCategory())) {
            List<String> childIdList = sysOrgMapper.findChildSysOrgListV2(Collections.singletonList(sysOrg.getId()))
                    .stream().map(SysOrg::getId).collect(Collectors.toList());
            stationgroupOrgIdList.addAll(childIdList);
        } else {
            //分支结构，只能使用本组织内设备组，或上级组织内的设备组
            stationgroupOrgIdList.add(sysOrg.getParentId());
            SysOrg parentOrg = sysOrgMapper.selectById((sysOrg.getParentId()));
            if (manageOneList.contains(parentOrg.getId())) {
                //如果登录用户有其客户的管理权限
                //找到所有可管理客户下分支机构
                List<String> childIdList = sysOrgMapper.findChildSysOrgListV2(Arrays.asList(parentOrg.getId())).stream().map(SysOrg::getId).collect(Collectors.toList());
                stationgroupOrgIdList.addAll(childIdList);
            }
        }
        if (!isAdmin) {
            //如果不是超级管理员，取用户所属组织ID和登录用户可管理组织ID交集
            stationgroupOrgIdList = stationgroupOrgIdList.stream().filter(it -> manageOrgIdList.contains(it)).collect(Collectors.toList());
            if (stationgroupOrgIdList.isEmpty()) {
                //没有交集，直接返回空
                return new ArrayList<>();
            }
        }
        //找出所有设备组
        QueryWrapper<SysStationGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("org_id", stationgroupOrgIdList);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 检查属于分支机构的设备组下的设备是否被授权
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkEquipmentAuth() {
        //所有要删除的数据ID
        List<Integer> deleteIdList = new ArrayList<>();
        //找出所有属于分支机构的设备组
        List<SysStationGroup> groupList = this.baseMapper.findStationgroupBelongOrg();
        //设备组按分支机构分组
        Map<String, List<SysStationGroup>> groupMap = groupList.stream()
                .collect(Collectors.groupingBy(SysStationGroup::getOrgId));
        //每个分支机构检查下面的设备组下的设备是否已经被授权
        groupMap.keySet().forEach(orgId -> {
            //分支机构下所有设备组ID
            List<String> groupIdList = groupMap.get(orgId).stream().map(SysStationGroup::getId).collect(Collectors.toList());
            //查询设备组下所有设备
            QueryWrapper<SysStationGroupEquipment> equipmentQueryWrapper = new QueryWrapper<>();
            equipmentQueryWrapper.in("group_id", groupIdList);
            List<SysStationGroupEquipment> equipmentList = sysStationGroupEquipmentMapper.selectList(equipmentQueryWrapper);
            //设备组下满有设备时采取检查
            if (!equipmentList.isEmpty()) {
                //找到所有上级授权的设备组
                List<String> authedGroupIdList = sysOrgStationGroupMapper.selectByMap(ImmutableMap.of("org_id", orgId))
                        .stream().map(SysOrgStationGroup::getGroupId).collect(Collectors.toList());
                //如果没有上级授权的设备组，那所有的都是要删除的
                if (authedGroupIdList.isEmpty()) {
                    equipmentList.forEach(it -> deleteIdList.add(it.getId()));
                } else {
                    //上级授权的设备组下所有设备
                    QueryWrapper<SysStationGroupEquipment> authedWrapper = new QueryWrapper<>();
                    authedWrapper.in("group_id", authedGroupIdList);
                    List<SysStationGroupEquipment> authedList = sysStationGroupEquipmentMapper.selectList(authedWrapper);
                    List<String> authedStationList = authedList.stream().filter(it -> !StringUtils.isEmpty(it.getStationId()))
                            .map(SysStationGroupEquipment::getStationId).collect(Collectors.toList());
                    List<String> authedEquipmentList = authedList.stream().filter(it -> !StringUtils.isEmpty(it.getEquipmentId()))
                            .map(SysStationGroupEquipment::getEquipmentId).collect(Collectors.toList());
                    //所有设备里面如果有设备不在授权的里面，都是要删除的数据，收集数据ID
                    deleteIdList.addAll(equipmentList.stream().filter(it -> {
                        if (!StringUtils.isEmpty(it.getStationId())) {
                            if (!authedStationList.contains(it.getStationId())) {
                                return true;
                            }
                            return false;
                        }
                        if (!StringUtils.isEmpty(it.getEquipmentId())) {
                            if (!authedEquipmentList.contains(it.getEquipmentId())) {
                                return true;
                            }
                            return false;
                        }
                        return true;
                    }).map(SysStationGroupEquipment::getId).collect(Collectors.toList()));
                }
            }
        });
        //删除未授权的数据
        if (!deleteIdList.isEmpty()) {
            sysStationGroupEquipmentMapper.deleteBatchIds(deleteIdList);
        }
    }
}
